//
//  LSWrongBookController.m
//  听说弱点强化训练
//
//  Created by 盛超 on 2018/9/9.
//  Copyright © 2018年 盛超. All rights reserved.
//

#import "LSWrongBookController.h"
#import "LSWrongBookCell.h"
#import "LSWrongBookManager.h"
#import "LSWrongCheckViewController.h"
#import "LSWrongQuesListManager.h"
#import "LSWrongQuesController.h"
#import "LSFtpManager.h"

@interface LSWrongBookController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView *bookTableView;
@property (nonatomic,assign) NSInteger pageSize;
@property (nonatomic,assign) NSInteger pageIndex;
@property (nonatomic,copy) NSString *type;
@property (nonatomic,strong) LSModelWrongBookList *model;
@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,assign) BOOL isNoMore;
@property (nonatomic,assign) BOOL isFooterRefresh;
@property (nonatomic,strong) UIButton *selectBtn;
@property (nonatomic,strong) UIView *selectShowView;
@property (nonatomic,assign) NSInteger selectIndex;
@property (nonatomic,strong) UIView *maskView;

@property (nonatomic,strong) UIImageView *noDataImageView;
@property (nonatomic,strong) UIView *footer;


@end

@implementation LSWrongBookController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我的错题本";
    self.view.backgroundColor = [UIColor colorWithHex:0xededed];
    [self addBYItemviews:@[@"LS-nav_back"] mode:ByNavigationItemModeImage position:ByNavigationItemPositionModeLeft];
    [self addCustomItemviews:@[self.selectBtn] position:ByNavigationItemPositionModeRight];
    
    UIImageView *navImageView = [[UIImageView alloc] init];
    navImageView.image = [UIImage imageNamed:@"LS-content_nav"];
    [self.view addSubview:navImageView];
    [navImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        make.height.mas_equalTo(kNavgationBar);
    }];
    
    self.pageIndex = 1;
    self.pageSize = 10;
    self.type = @"-1";
    self.dataArray = [NSMutableArray array];
    
    [self.view addSubview:self.bookTableView];
    self.footer = [self createFooter];
    self.footer.y = kHeight-kBottomPadding-60;
    [self.view addSubview:self.footer];
    
//    [MBProgressHUD showDefaultToView:self.view];
//
//    [self loadData];
}

#pragma mark - 其他
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setNaviAttributeWithTranslucent:YES stateBarLightContent:YES];
    
    [MBProgressHUD showDefaultToView:self.view];
    
    [self loadData];
}

- (void)leftItemsAction:(NSInteger)leftIndex {
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

- (void)loadData {
    LSWrongBookManager *manager = [[LSWrongBookManager alloc] init];
    NSDictionary *dict = @{@"StuID":DR_UserInfo.UserID,
                           @"StageNo":KGetUserDefaults(@"TestLayer"),
                           @"SchoolID":KGetUserDefaults(@"SchoolID"),
                           @"PageIndex":@(1),
                           @"PageSize":@(self.pageSize*self.pageIndex),
                           @"TypeID":self.type
                           };

    manager.requestParam = @{@"DictString":[NSObject objectToJson:dict]};
    
    WeakObj(self);
    [manager requestWithCompltionSuccess:^(LSModelWrongBookList *model) {
        
        selfWeak.model = model;
        
        if (_model.FtpServerAddress!=nil) {
            NSString *ftpServerAddress = _model.FtpServerAddress;
            NSString *ftpUserPwd = _model.sUserPwd;
            NSString *ftpUser = _model.sUserName;
            [ZBFtpTools ZBFtp_setupInitWithHost:ftpServerAddress
                                           user:ftpUser
                                            psw:ftpUserPwd];
        } else {
            [MBProgressHUD showText:@"错题获取错误" state:KZHUDStateModeFailure duration:2];
        }
        [selfWeak.dataArray removeAllObjects];
        [selfWeak.dataArray addObjectsFromArray:model.ItemInfoList];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [selfWeak.noDataImageView removeFromSuperview];
            selfWeak.footer.alpha = 1;
            
            [selfWeak.bookTableView reloadData];
            [MBProgressHUD hideHUDForView:selfWeak.view animated:YES];
            
            if (self.dataArray.count==model.TotalCount && self.dataArray.count!=0) {
                
                if (_isNoMore==YES&&_isFooterRefresh==YES) {
                    [MBProgressHUD showNoDataStyleToView:selfWeak.view];
                    [selfWeak.bookTableView.mj_footer endRefreshingWithNoMoreData];
                    selfWeak.bookTableView.mj_footer.hidden = YES;
                }
                
                _isNoMore = YES;
                
            } else if (self.dataArray.count==0) {
                
                [selfWeak.view addSubview:selfWeak.noDataImageView];
                selfWeak.footer.alpha = 0;
            }
            
            [selfWeak.bookTableView.mj_footer endRefreshing];
            [selfWeak.bookTableView.mj_header endRefreshing];
        });
      
    } failuer:^(NSString *error) {
        
         dispatch_async(dispatch_get_main_queue(), ^{
             
             [MBProgressHUD hideHUDForView:selfWeak.view animated:YES];
             [selfWeak.view addSubview:selfWeak.noDataImageView];
             selfWeak.footer.alpha = 0;

         });
    }];
}

#pragma mark - 没有数据
- (UIImageView *)noDataImageView {
    if (!_noDataImageView) {
        _noDataImageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
        
        UIImageView *imageView = [UIImageView new];
        imageView.image = [UIImage imageNamed:@"kz-暂无数据"];
        [_noDataImageView addSubview:imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(_noDataImageView);
            make.centerY.equalTo(_noDataImageView).offset(30);
        }];

    }
    
    return _noDataImageView;
}

#pragma mark - SelectBtn
- (UIButton *)selectBtn {
    if (!_selectBtn) {
        _selectBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0,100,40)];
        [_selectBtn setTitle:@"全部题型" forState:UIControlStateNormal];
        _selectBtn.titleLabel.font = FONT(15);
        _selectBtn.titleLabel.textAlignment = NSTextAlignmentLeft;
        [_selectBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_selectBtn setImage:[UIImage imageNamed:@"LS-箭头-1"] forState:UIControlStateNormal];
        [_selectBtn setImage:[UIImage imageNamed:@"LS-箭头-2"] forState:UIControlStateSelected];
        [_selectBtn addTarget:self action:@selector(selectRefreshing:) forControlEvents:UIControlEventTouchUpInside];
        _selectBtn.imageEdgeInsets = UIEdgeInsetsMake(0,80,0,-80);
        _selectBtn.titleEdgeInsets = UIEdgeInsetsMake(0,5,0,-5);
    }
    return _selectBtn;
}

- (UIView *)selectShowView {
    if (!_selectShowView) {
        UIView *maskView = [[UIView alloc] initWithFrame:CGRectMake(0, kNavgationBar, kWidth, kHeight-kNavgationBar-kBottomPadding)];
        self.maskView = maskView;
        maskView.backgroundColor = RGBA(0, 0, 0, 0.3);
        [self.view addSubview:maskView];
        [maskView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideSelectView)]];
        
        _selectShowView = [[UIView alloc] initWithFrame:CGRectMake(kWidth-120,-200,120,160)];
        _selectShowView.backgroundColor = [UIColor whiteColor];
        NSArray *titles = @[@"全部题型",@"听力选择",@"朗读短文",@"句子跟读"];
        for (NSInteger i = 0; i<4; i++) {
            UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0,i*40+10,120,30)];
            btn.titleLabel.font = [UIFont systemFontOfSize:15];
            btn.titleLabel.textAlignment = NSTextAlignmentCenter;
            [btn setTitle:titles[i] forState:UIControlStateNormal];
            [btn addTarget:self action:@selector(selectBtnAction:) forControlEvents:UIControlEventTouchUpInside];
            if (_selectIndex==i) {
                [btn setTitleColor:[UIColor colorWithHex:0x2aabf6] forState:UIControlStateNormal];
            } else {
                [btn setTitleColor:[UIColor colorWithHex:0x797979] forState:UIControlStateNormal];
            }
            btn.tag = 1000+i;
            [_selectShowView addSubview:btn];
            
            if (i!=3) {
                UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(10,btn.y+btn.height+5,100, 0.5)];
                line.backgroundColor = [[UIColor colorWithHex:0x797979] colorWithAlphaComponent:0.5];
                [_selectShowView addSubview:line];
            }
        }
        
        [self.view addSubview:_selectShowView];
    }
    return _selectShowView;
}

#pragma mark - TableView
- (UITableView *)bookTableView {
    if (!_bookTableView) {
        _bookTableView = [[UITableView alloc] initWithFrame:CGRectMake(0,kNavgationBar, kWidth, kHeight-kNavgationBar-kBottomPadding-60) style:UITableViewStyleGrouped];
        _bookTableView.backgroundColor = [UIColor colorWithHex:0xededed];
        _bookTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _bookTableView.delegate = self;
        _bookTableView.dataSource = self;
        [_bookTableView registerClass:[LSWrongBookCell class] forCellReuseIdentifier:@"LSWrongBookCell"];
        _bookTableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 1)];
        
        _bookTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefreshing)];
        MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefreshing)];
        footer.stateLabel.hidden = YES;
        footer.refreshingTitleHidden = YES;
        _bookTableView.mj_footer = footer;
    }
    return _bookTableView;
}

- (UIView*)createFooter {
    UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 60)];
    backView.backgroundColor = [UIColor whiteColor];
    
    UIButton *wrongReAnswerBtn = [[UIButton alloc] init];
    wrongReAnswerBtn.frame = CGRectMake(10, 10, kWidth-20, 40);
    wrongReAnswerBtn.layer.cornerRadius = 6;
    wrongReAnswerBtn.layer.masksToBounds = YES;
    [wrongReAnswerBtn gradientButtonWithSize:CGSizeMake(wrongReAnswerBtn.width,wrongReAnswerBtn.height) colorArray:@[[UIColor colorWithHex:0x09b9f3], [UIColor colorWithHex:0x1a9ff8]] percentageArray:@[@0,@1] gradientType:GradientFromLeftToRight];
    [wrongReAnswerBtn addTarget:self action:@selector(enterWrongReAnswer) forControlEvents:UIControlEventTouchUpInside];
    [wrongReAnswerBtn setTitle:@"错题重做" forState:UIControlStateNormal];
    [backView addSubview:wrongReAnswerBtn];

    return backView;
}

- (void)enterWrongReAnswer {

    LSWrongQuesListManager *manager = [[LSWrongQuesListManager alloc] init];
    NSDictionary *dict = @{@"StuID":DR_UserInfo.UserID,
                           @"SchoolID":KGetUserDefaults(@"SchoolID"),
                           @"StageNo":KGetUserDefaults(@"TestLayer"),
                           @"TypeID":@"-1"
                           };
    manager.requestParam = @{@"DictString":[NSObject objectToJson:dict]};
    WeakObj(self);
    [manager requestWithCompltionSuccess:^(LSModelWrongQuesList *model) {
    
        if (model.FtpServerAddress != nil) {
            NSString *ftpServerAddress = model.FtpServerAddress;
            NSString *ftpUserPwd = model.sUserPwd;
            NSString *ftpUser = model.sUserName;
            [ZBFtpTools ZBFtp_setupInitWithHost:ftpServerAddress
                                           user:ftpUser
                                            psw:ftpUserPwd];
            LSWrongQuesController *vc = [[LSWrongQuesController alloc] init];
            vc.model = model;
            [selfWeak push:vc];
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showText:@"请求数据错误" state:KZHUDStateModeFailure duration:2];
            });
        }
      
    } failuer:^(NSString *error) {
        
    }];
}

- (void)headerRefreshing {
    _isFooterRefresh = NO;
    _isNoMore = NO;
    self.bookTableView.mj_footer.hidden = NO;
    
    self.pageSize = 10;
    self.pageIndex = 1;
    [self.dataArray removeAllObjects];
    
    [self loadData];
}

- (void)footerRefreshing {
    _isFooterRefresh = YES;
    
    self.pageIndex = self.pageIndex+1;
    self.pageSize = 10;
    
    [self loadData];
}

- (void)selectRefreshing:(UIButton*)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        [self showSelectView];
    } else {
        [self hideSelectView];
    }
}

- (void)showSelectView {
    
    self.maskView.alpha = 1;
    [self.view bringSubviewToFront:self.maskView];
    self.selectShowView.y = kNavgationBar;
    [self.view bringSubviewToFront:self.selectShowView];
    self.selectBtn.selected = YES;
}

- (void)hideSelectView {

    self.maskView.alpha = 0;
    
    self.selectShowView.y = -200;
    
    self.selectBtn.selected = NO;
}

- (void)selectBtnAction:(UIButton*)sender {
    
    for (NSInteger i = 0; i<4; i++) {
        UIButton *btn = [self.selectShowView viewWithTag:1000+i];
        [btn setTitleColor:[UIColor colorWithHex:0x797979] forState:UIControlStateNormal];
    }
    [sender setTitleColor:[UIColor colorWithHex:0x2aabf6] forState:UIControlStateNormal];
    [self hideSelectView];
    
    self.selectBtn.selected  = NO;
    
    if (sender.tag==1000) {
        _type = @"-1";
        _selectIndex = 0;
        [self.selectBtn setTitle:@"全部题型" forState:UIControlStateNormal];
        self.selectBtn.imageEdgeInsets = UIEdgeInsetsMake(0,80,0,-80);
        self.selectBtn.titleEdgeInsets = UIEdgeInsetsMake(0,5,0,-5);
    } else if (sender.tag==1001) {
        _type = @"SE";
        _selectIndex = 1;
        [self.selectBtn setTitle:@"听力选择" forState:UIControlStateNormal];
        self.selectBtn.imageEdgeInsets = UIEdgeInsetsMake(0,80,0,-80);
        self.selectBtn.titleEdgeInsets = UIEdgeInsetsMake(0,5,0,-5);
    } else if (sender.tag==1002) {
        _type = @"Spn";
        _selectIndex = 2;
        [self.selectBtn setTitle:@"朗读短文" forState:UIControlStateNormal];
//        self.selectBtn.imageEdgeInsets = UIEdgeInsetsMake(0,60,0,-60);
//        self.selectBtn.titleEdgeInsets = UIEdgeInsetsMake(0,15,0,-15);
        self.selectBtn.imageEdgeInsets = UIEdgeInsetsMake(0,80,0,-80);
        self.selectBtn.titleEdgeInsets = UIEdgeInsetsMake(0,5,0,-5);

    } else if (sender.tag==1003) {
        _type = @"Sq";
        _selectIndex = 3;
        [self.selectBtn setTitle:@"句子跟读" forState:UIControlStateNormal];
//        self.selectBtn.imageEdgeInsets = UIEdgeInsetsMake(0,60,0,-60);
//        self.selectBtn.titleEdgeInsets = UIEdgeInsetsMake(0,15,0,-15);
        self.selectBtn.imageEdgeInsets = UIEdgeInsetsMake(0,80,0,-80);
        self.selectBtn.titleEdgeInsets = UIEdgeInsetsMake(0,5,0,-5);
    }
  
    [MBProgressHUD showDefaultToView:self.view];
    [self headerRefreshing];
}

#pragma mark - DataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
     return self.dataArray.count;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LSWrongBookCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LSWrongBookCell"];
    cell.model = self.dataArray[indexPath.section];
    
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}


#pragma mark - Delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 125;
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 5)];
}

- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 5)];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 5;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    LSWrongCheckViewController *vc = [[LSWrongCheckViewController alloc] init];
    LSWrongBookItem * model = self.dataArray[indexPath.section];
    vc.item = model;
    
    [self push:vc];
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
- (void)dealloc {
    NSLog(@"销毁");
}


@end
